package com.nanbei.future;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @ClassDescription: 使用4种静态方法调用 CompletableFuture
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/9/25 16:15
 */
public class CompletableFutureDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        // 没有返回值的 CompletableFuture
        /*CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName());
        },threadPool);*/

        // 有返回值的 CompletableFuture
        /*CompletableFuture<String> stringCompletableFuture =
                CompletableFuture.supplyAsync(() -> Thread.currentThread().getName(),threadPool);
        System.out.println(stringCompletableFuture.get());*/

        // CompletableFuture.supplyAsync()，默认情况下它会使用 ForkJoinPool.commonPool()
        // ForkJoinPool.commonPool() 中的线程是守护线程 所以主线程结束后该线程也结束了
        try {
            CompletableFuture.supplyAsync(() -> {
                // 1s 后返回一个随机数作为下一步的结果
                System.out.println(Thread.currentThread().getName()+"come in ...");
                Random random = new Random();
                int i = random.nextInt(10);
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                    System.out.println("1s 后生成一个随机数" + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (i < 5 ){
                    throw new RuntimeException();
                }
                return i;
            },threadPool).whenComplete((value,e)->{  // value为上一步结果的返回值
                if (e == null){
                    System.out.println("value值大于等于 5 ，其value值为："+value);
                }
            }).exceptionally(e->{
                System.out.println("value值小于 5 ");
                return null;
            });

            System.out.println("main线程继续执行其它的任务。。。。。");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }
}
